package com.heyige.interceptor;

import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import com.heyige.exception.BusinessException;
import com.heyige.exception.ErrorCode;
import com.heyige.util.JwtUtil;
import com.heyige.util.RedisUtil;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Component
@RequiredArgsConstructor
public class JwtInterceptor implements HandlerInterceptor {

    private final JwtUtil jwtUtil;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 从请求头获取token
        String token = request.getHeader("Authorization");

        // 如果没有token，尝试从请求头获取
        if (token == null || token.isEmpty()) {
            token = request.getHeader("accessToken");
        }

        // 如果没有token，尝试从参数获取
        if (token == null || token.isEmpty()) {
            token = request.getParameter("token");
        }

        // 如果还是没有token，返回401
        if (token == null || token.isEmpty()) {
            throw new BusinessException(ErrorCode.USER_NOT_LOGIN);
        }

        // 去除Bearer前缀
        if (token.startsWith("Bearer ")) {
            token = token.substring(7);
        }

        // 验证token是否在黑名单中
        String blacklistKey = "jwt:blacklist:" + token;
        if (RedisUtil.hasKey(blacklistKey)) {
            throw new BusinessException(ErrorCode.USER_TOKEN_INVALID);
        }

        // 验证token
        try {
            if (!jwtUtil.isTokenValid(token)) {
                throw new BusinessException(ErrorCode.USER_TOKEN_INVALID);
            }

            // 将用户信息存入请求属性
            Long userId = jwtUtil.extractUserId(token);
            String username = jwtUtil.extractUsername(token);

            request.setAttribute("userId", userId);
            request.setAttribute("username", username);

            return true;
        } catch (Exception e) {
            log.error("JWT验证失败: {}", e.getMessage());
            throw new BusinessException(ErrorCode.USER_TOKEN_INVALID);
        }
    }
}